package com.pine.app.module.security.oauth.user.service;

import com.pine.app.module.security.core.common.AuthConstant;
import com.pine.app.module.security.core.userdetails.UserDetails;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.common.enums.ResponseProduceType;
import com.pine.app.module.security.oauth.exception.AuthenticationException;
import com.pine.app.module.security.oauth.exception.BadCredentialsException;
import com.pine.app.module.security.oauth.plugin.Plugin;
import com.pine.app.module.security.oauth.support.password.HttpPasswordRequest;
import com.pine.app.module.security.oauth.user.password.PasswordVerifiers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author xiaoyuan
 * @create 2020/3/7 13:28
 **/

public class LoginServiceImpl implements LoginService {


    private UserDetailService userDetailService;

    private PasswordVerifiers passwordVerifiers;

    @Autowired
    public void setUserDetailService(UserDetailService userDetailService) {
        this.userDetailService = userDetailService;
    }
    @Autowired
    public void setPasswordVerifiers(PasswordVerifiers passwordVerifiers) {
        this.passwordVerifiers = passwordVerifiers;
    }

    @Plugin(value = {"loginService"})
    @Override
    public UserDetails login(HttpPasswordRequest request) {
        return login(request, ResponseProduceType.JSON);
    }

    @Plugin(value = {"loginService"},responseType = ResponseProduceType.HTML)
    @Override
    public UserDetails login(HttpPasswordRequest request, ResponseProduceType responseProduceTypeEnum) {
        UserDetails userDetails = userDetailService.loadUserByUsername(request.getUsername());
        if (userDetails == null || StringUtils.isEmpty(userDetails.getUsername()) || StringUtils.isEmpty(userDetails.getPassword())) {
            throw new AuthenticationException( ErrorType.ILLEGAL_USERNAME_OR_PASSWORD,responseProduceTypeEnum, AuthConstant.DEFAULT_LOGIN_PATH);
        }
        boolean result = this.passwordVerifiers.verifiers(
                userDetails.getPassword(), request.getPassword());

        if (!result) {
            throw new BadCredentialsException( ErrorType.ILLEGAL_USERNAME_OR_PASSWORD, responseProduceTypeEnum,AuthConstant.DEFAULT_LOGIN_PATH);
        }
        if (userDetails.isEnabled()) {
            throw new AuthenticationException( ErrorType.EXPIRED_CODE, responseProduceTypeEnum,AuthConstant.DEFAULT_LOGIN_PATH);
        }
        if (!userDetails.isAccountNonLocked()) {
            throw new AuthenticationException( ErrorType.ACCOUNT_NONLOCKED, responseProduceTypeEnum,AuthConstant.DEFAULT_LOGIN_PATH);
        }
        if (!userDetails.isAccountNonExpired()) {
            throw new AuthenticationException( ErrorType.ACCOUNT_NONEXPIRED,responseProduceTypeEnum,AuthConstant.DEFAULT_LOGIN_PATH);
        }
        return userDetails;
    }
}
